package datamodels

import (
	"micro-oauth/utils"
	"time"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres"
)

type MyGormModel struct {
	Id        uint64     `json:"id,string" gorm:"type:int8;primary_key" sql:"default:0"`
	CreatedAt time.Time  `json:"created_at" gorm:"index;type:timestamptz;"`
	UpdatedAt time.Time  `json:"updated_at" gorm:"index;type:timestamptz;"`
	DeletedAt *time.Time `json:"-" gorm:"index;type:timestamptz;"`
	CreatedBy uint64     `json:"created_by,string" grom:"type:int8;"`
	UpdatedBy uint64     `json:"updated_by,string"`
	Opts []OrmOpt        `json:"-"gorm:"-"`
}

type OrmOpts struct {
	ScopeId uint64
}


type OrmOpt func (o *OrmOpts)

func WithScope(scopeId uint64)OrmOpt{
	return func(o *OrmOpts) {
		o.ScopeId = scopeId
	}
}

func (m *MyGormModel) BeforeCreate() error {
	defaultOpt := &OrmOpts{}
	for _, o := range m.Opts {
		o(defaultOpt)
	}
	if len(m.Opts) > 0 {
		m.Id = defaultOpt.ScopeId
	}
	if len(m.Opts) == 0 {
		if m.Id == 0 {
			m.Id, _ = utils.GetId()
		}
	}
	return nil
}

var db *gorm.DB

const tableNamePrefix = "oauth_"

func SetDB(_db *gorm.DB) {
	db = _db
	db.SingularTable(true)
}

func CloseDB() {
	_ = db.Close()
	db.SingularTable(true)
}

func EnableDBLog() {
	db = db.LogMode(true)
}

func init() {
	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		return tableNamePrefix + defaultTableName
	}
}
